<?php
// +----------------------------------------------------------------------
// | MC PHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------

namespace app\common\model;

use think\facade\Cache;

/**
 * 接口字段模型
 * 用于保存各个API的字段规则
 * @package app\common\model
 * @Author jokerfei [ jokerfei377@gmail.com ]
 */
class Apifields extends BaseModel
{

    protected $name = 'system_api_fields';
    //只读字段,一旦写入，就无法更改。
    protected $readonly = ['hash'];
    // 新增自动完成列表
    protected array $insert = [];
    //更新自动完成列表
    protected array $update = [];
    //新增和更新自动完成列表
    protected array $auto = [];
    //字段类型
    public array $datatype = array(
        1  => 'Integer[整数]',
        2  => 'String[字符串]',
        3  => 'Boolean[布尔]',
        4  => 'Enum[枚举]',
        5  => 'Float[浮点数]',
        6  => 'File[文件]',
        7  => 'Mobile[手机号]',
        8  => 'Object[对象]',
        9  => 'Array[数组]',
        10 => 'Email[邮箱]',
        11 => 'Date[日期]',
        12 => 'Url',
        13 => 'IP',
    );

    /**
     * 是否必填获取器
     * @param $value
     * @param $data
     * @return string
     * @Author jokerfei [ jokerfei377@gmail.com ]
     */
    public function getIsmustTurnAttr($value, $data)
    {
        //是否必须 ismust 字段 [获取器]
        $turnArr = [0 => '选填', 1 => '必填'];
        return $turnArr[$data['ismust']];
    }

    /**
     * 类型获取器
     * @param $value
     * @param $data
     * @return string
     * @Author jokerfei [ jokerfei377@gmail.com ]
     */
    public function getDatatypeTurnAttr($value, $data)
    {
        //字段类型 datatype 字段 [获取器]
        $turnArr = [
            1  => 'Integer[整数]',
            2  => 'String[字符串]',
            3  => 'Boolean[布尔]',
            4  => 'Enum[枚举]',
            5  => 'Float[浮点数]',
            6  => 'File[文件]',
            7  => 'Mobile[手机号]',
            8  => 'Object[对象]',
            9  => 'Array[数组]',
            10 => 'Email[邮箱]',
            11 => 'Date[日期]',
            12 => 'Url',
            13 => 'IP',
        ];
        return $turnArr[$data['datatype']];
    }

    /**
     * 获取缓存字段
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @param string $hash 接口HASH
     * @param int $type
     * @return array|null
     */
    public static function getCacheFields(string $hash, int $type = 1)
    {
        // 生产模式，获取缓存数据
        if (!config('cache.develop_mode')) {
            $key    = "apiFields_" . $hash . '_' . $type;
            $fields = cache($key);
            if (empty($fields)) {
                $map['hash'] = $hash;
                $map['type'] = $type;
                $fields      = (new Apifields)->where($map)->select()->toArray(); //获取数据库的请求字段
                Cache::tag('api')->set($key, $fields, 7200);
            }
        }
        else {
            // 开发模式，直接获取最新数据
            $map['hash'] = $hash;
            $map['type'] = $type;
            $fields      = (new Apifields)->where($map)->select()->toArray(); //获取数据库的请求字段
        }
        return $fields;
    }

    //获取缓存规则
    public static function cacheBuildValidateRule($rule)
    {
        // 生产模式，获取缓存数据
        if (!config('cache.develop_mode')) {
            $key     = "apiRule_" . md5(json_encode($rule));
            $newRule = cache($key);
            if (empty($newRule)) {
                $newRule = self::buildValidateRule($rule);
                Cache::tag('api')->set($key, $newRule, 7200); //接口信息
            }
        }
        else {
            // 开发模式，直接获取最新数据
            $newRule = self::buildValidateRule($rule);
        }
        return $newRule;
    }

    /**
     * 将数据库中的规则转换成TP_Validate使用的规则数组
     * @param array $rule
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @return array
     */
    public static function buildValidateRule($rule = array())
    {
        $newRule = [];
        if ($rule) {
            foreach ($rule as $value) {
                if ($value['ismust'] && $value['default'] == '') {
                    $newRule[$value['fieldname']][] = 'require'; //必填
                }
                switch ($value['datatype']) {
                    case 1: //Integer[整数]
                        $newRule[$value['fieldname']][] = 'number';
                        if ($value['range']) {
                            $range = htmlspecialchars_decode($value['range']);
                            $range = json_decode($range, true);
                            if (isset($range['min'])) {
                                $newRule[$value['fieldname']]['egt'] = $range['min']; // >= 大于等于
                            }
                            if (isset($range['max'])) {
                                $newRule[$value['fieldname']]['elt'] = $range['max']; // <= 小于等于
                            }
                        }
                        break;
                    case 2: //String[字符串]
                        if ($value['range']) {
                            $range = htmlspecialchars_decode($value['range']);
                            $range = json_decode($range, true);
                            if (isset($range['min'])) {
                                $newRule[$value['fieldname']]['min'] = $range['min']; //最小长度
                            }
                            if (isset($range['max'])) {
                                $newRule[$value['fieldname']]['max'] = $range['max']; //最大长度
                            }
                        }
                        break;
                    case 3: //Boolean[布尔]
                        $newRule[$value['fieldname']][] = 'boolean';
                        break;
                    case 4: //Enum[枚举]
                        if ($value['range']) {
                            $range                              = htmlspecialchars_decode($value['range']);
                            $range                              = json_decode($range, true);
                            $newRule[$value['fieldname']]['in'] = implode(',', $range);
                        }
                        break;
                    case 5: //Float[浮点数]
                        $newRule[$value['fieldname']][] = 'float';
                        if ($value['range']) {
                            $range = htmlspecialchars_decode($value['range']);
                            $range = json_decode($range, true);
                            if (isset($range['min'])) {
                                $newRule[$value['fieldname']]['egt'] = $range['min']; // >= 大于等于
                            }
                            if (isset($range['max'])) {
                                $newRule[$value['fieldname']]['elt'] = $range['max']; // <= 小于等于
                            }
                        }
                        break;
                    case 6: //File[文件]
                        $newRule[$value['fieldname']][] = 'file';
                        break;
                    case 7: //Mobile[手机号]
                        $newRule[$value['fieldname']][] = 'mobile';
                        break;
                    case 9: //Array[数组]
                        $newRule[$value['fieldname']][] = 'array';
                        if ($value['range']) {
                            $range = htmlspecialchars_decode($value['range']);
                            $range = json_decode($range, true);
                            if (isset($range['min'])) {
                                $newRule[$value['fieldname']]['min'] = $range['min']; //最小长度
                            }
                            if (isset($range['max'])) {
                                $newRule[$value['fieldname']]['max'] = $range['max']; //最大长度
                            }
                        }
                        break;
                    case 10: //Email[邮箱]
                        $newRule[$value['fieldname']][] = 'email';
                        break;
                    case 11: //Date[日期]
                        $newRule[$value['fieldname']][] = 'date';
                        break;
                    case 12: //Url
                        $newRule[$value['fieldname']][] = 'url';
                        break;
                    case 13: //IP
                        $newRule[$value['fieldname']][] = 'ip';
                        break;
                    default:
                        $newRule[$value['fieldname']][] = '';
                }
            }
        }
        return $newRule;
    }

}
